/*
 * @Description: 元数据列表
 * @Author: Rfan
 * @Date: 2022-01-20 15:45:14
 * @LastEditTime: 2022-06-16 17:02:21
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table, Tag } from 'antd';
import classNames from 'classnames/bind';
import { useMetadataInheritContext } from '../contexts/MetadataInheritContext';
import { selectItemByKey } from '@/utils/list';
import { useFormatMessage } from '@/utils/intlHelpers';

import styles from '../styles/metadataPane.module.scss';
import PaneOperate from './PaneOperate';
import { IPageQuery } from '@/interfaces/global';
import { isNullObj } from '@/utils';
import EditDialog from './dialogs/EditDialog';

const cx = classNames.bind(styles);

const { Column } = Table;

const InheritListPane = ({ title, data }: any) => {
  const formatMessage = useFormatMessage();
  const {
    selectAT,
    selectLevel,
    inheritList,
    getInheritList,
    selectItems,
    setSelectKey,
    deleteInheritFunc,
    stateNameFilter,
    stateColorFilter,
    linkageStateNameFilter,
    linkageStateColorFilter
  } = useMetadataInheritContext();

  // 表格加载
  const [loading, setLoading] = useState(false);
  // 总条目数
  const [total, setTotal] = useState(0);
  // 表格请求参数
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  // 编辑弹窗显示状态
  const [editDialogVisible, setEditDialogVisible] = useState(false);
  // 选中的条目数据
  const [selectData, setSelectData] = useState({});

  useEffect(() => {
    if (selectAT.id && (selectLevel.level === 0 || selectLevel.level)) {
      setListQuery((state) => ({
        ...state,
        param: {
          ...state.param,
          relationType: 0,
          atType: selectAT.atType,
          atCode: selectAT.atCode,
          level: selectLevel.level
        }
      }));
    }
  }, [selectAT, selectLevel]);

  useEffect(() => {
    if (listQuery.param && !isNullObj(listQuery.param)) {
      setLoading(true);
      setLoading(false);
      setTotal(0);
      getInheritList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const showEditDialog = (data: any) => {
    setSelectData(data);
    setEditDialogVisible(true);
  };

  return (
    <div className={cx('metadata-pane')}>
      <PaneOperate title={title} data={data} />
      <div className={cx('container')}>
        <Table
          dataSource={inheritList}
          loading={loading}
          rowKey="id"
          rowSelection={rowSelection}
          bordered
          scroll={{
            x: 'max-content'
          }}
          pagination={{
            current: listQuery.pageNo,
            pageSize: listQuery.pageSize,
            total,
            onChange: pageChange
          }}
        >
          <Column title="序号" dataIndex="id" key="id" align="center" />
          <Column
            title="层级"
            dataIndex="level"
            key="level"
            align="center"
            render={(val: number) => {
              const _level: any = selectItemByKey(val, selectAT.levelList, 'level');
              return _level?.levelName;
            }}
          />
          <Column
            title="字段"
            dataIndex={['targetData', 'field_desc']}
            key="field_name"
            align="center"
          />
          <Column
            title="继承的层级"
            dataIndex={['inheritRuleData', 'level']}
            key="inheridLevel"
            align="center"
            render={(val: number) => {
              const _level: any = selectItemByKey(val, selectAT.levelList, 'level');
              return _level?.levelName;
            }}
          />
          <Column
            title="继承的字段"
            dataIndex={['inheritRuleData', 'field_desc']}
            key="inheritField"
            align="center"
          />
          <Column
            title="状态"
            dataIndex="isValid"
            key="isValid"
            align="center"
            render={(val: number) => (
              <Tag color={stateColorFilter(val)}>{stateNameFilter(val)}</Tag>
            )}
          />
          <Column
            title="是否联动"
            dataIndex="isLinkage"
            key="inheritRule"
            align="center"
            render={(val: number) => (
              <Tag color={linkageStateColorFilter(val)}>{linkageStateNameFilter(val)}</Tag>
            )}
          />
          <Column
            title={formatMessage('tableAction')}
            key="action"
            align="center"
            render={(_text, record: any) => (
              <Space>
                <Button
                  type="link"
                  onClick={() => {
                    showEditDialog(record);
                  }}
                >
                  修改
                </Button>
                <Button
                  type="link"
                  danger
                  onClick={() => {
                    deleteInheritFunc(record.id);
                  }}
                >
                  删除
                </Button>
              </Space>
            )}
          />
        </Table>
      </div>
      {useMemo(
        () => (
          <EditDialog
            visible={editDialogVisible}
            data={selectData}
            onClose={() => {
              setEditDialogVisible(false);
            }}
          />
        ),
        [editDialogVisible]
      )}
    </div>
  );
};

export default InheritListPane;
